const sha1 = require("sha1")
const {weChatConfig} = require("../config/AuthConfig")
const {HandlePostMsg} = require("../router_handler/wechat");
module.exports = () => {
    return async (req, res, next) => {
        const {signature, echostr, timestamp, nonce} = req.query
        const {token} = weChatConfig
        const sha1Str = sha1([token, timestamp, nonce].sort().join(""))
        if (req.method === "GET") {
            if (sha1Str === signature) {
                return res.send(echostr)
            } else {
                // 验证失败，返回403
                next()
            }
        } else if (req.method === "POST") {
            if (sha1Str === signature) {
                console.log("post-req")
                await HandlePostMsg(req, res)
                // await HandlePostMsg(req, res)
            } else {
                next()
            }
        } else next()
    }
}